package service

import (
	"admin-system-go/model"
	"admin-system-go/model/do"
	"admin-system-go/model/dto"
	"admin-system-go/repository"
	"fmt"
)

type UserGroupService interface {
	QueryUserGroup(dto dto.UserGroupQueryDTO) model.ResponseEntity
	CreateUserGroup(dto dto.UserGroupBaseDTO) model.ResponseEntity
	DelUserGroup(dto dto.UserGroupDelDTO) model.ResponseEntity
	UpdateUserGroup(updateDTO dto.UserGroupUpdateDTO) model.ResponseEntity
}

type userGroupServiceImpl struct{}

func (userGroupService userGroupServiceImpl) QueryUserGroup(queryDto dto.UserGroupQueryDTO) model.ResponseEntity {
	var userGroup do.UserGroup
	_ = repository.Copy(userGroup, &queryDto)
	var userGroups []do.UserGroup
	pageSize := queryDto.PageSize
	pageNo := queryDto.PageNo
	var total int64
	_ = repository.GetDb().Where(&userGroup).Limit(pageSize).Offset((pageNo - 1) * pageSize).Find(&userGroups)
	var result = make([]dto.UserGroupQueryDTO, len(userGroups))
	if len(userGroups) != 0 {
		_ = repository.GetDb().Model(&do.UserGroup{}).Where(&userGroup).Count(&total)
	}
	_ = repository.CopySlice(userGroups, result)
	return model.PageEntityModel(result, &model.PageInfo{
		Total:    total,
		PageSize: pageSize,
		PageNo:   pageNo,
	})
}

func (userGroupService userGroupServiceImpl) CreateUserGroup(createDto dto.UserGroupBaseDTO) model.ResponseEntity {
	var userGroup do.UserGroup
	_ = repository.Copy(createDto, &userGroup)
	tx := repository.GetDb().Where(&do.UserGroup{Name: createDto.Name}).Find(&userGroup)
	if tx.RowsAffected > 0 {
		return model.FailEntityModel("用户组已经存在")
	}
	tx = repository.GetDb().Create(&userGroup)
	return model.BoolEntityModel(tx.RowsAffected == 1, tx.Error)
}

func (userGroupService userGroupServiceImpl) DelUserGroup(delDto dto.UserGroupDelDTO) model.ResponseEntity {
	tx := repository.GetDb().Begin()
	defer func() {
		err := recover()
		if err != nil {
			fmt.Println(err)
			tx.Rollback()
		}
	}()
	tx.Where("group_id IN ?", delDto.UserGroupIds).Delete(&do.GroupUser{})
	tx.Delete(&do.UserGroup{}, delDto.UserGroupIds)
	tx.Commit()
	return model.BoolEntityModel(tx.Error == nil, tx.Error)
}

func (userGroupService userGroupServiceImpl) UpdateUserGroup(updateDTO dto.UserGroupUpdateDTO) model.ResponseEntity {

	var oldUserGroupDo do.UserGroup = do.UserGroup{Model: model.Model{Id: updateDTO.Id}}
	tx := repository.GetDb().Model(&oldUserGroupDo).Find(&oldUserGroupDo)
	if tx.RowsAffected == 0 {
		return model.FailEntityModel("用户组不存在")
	}
	_ = repository.Copy(updateDTO, &oldUserGroupDo)
	tx = repository.GetDb().Model(&oldUserGroupDo).Save(&oldUserGroupDo)
	if tx.Error == nil {
		return model.SuccessEntityModel(true)
	} else {
		return model.FailEntityModel("更新失败")
	}
}
